package no.ffi.gismoidm.servicestubs;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.security.PublicKey;
import no.ffi.gismoidm.idp.Config;
import no.ffi.gismoidm.idp.IdentityStatementIssuer;
import no.ffi.gismoidm.utils.IdentityStatement;
import no.ffi.gismoidm.utils.EncryptedIdentityStatement;
import no.ffi.gismoidm.utils.GismoIdmException;
import no.ffi.tpm.LegacyKeyCertifyInfo;
import no.ffi.tpm.TPMiSRequest;
import no.ffi.tpm.crypto.CryptoOperations;
import no.ffi.tpm.crypto.CryptoOperationsFactory;

public class IdPServiceHost {
 
    CryptoOperations myCrOp;
    // Constructor used by servlet which has already loaded the properties file
    public IdPServiceHost() {
        myCrOp = CryptoOperationsFactory.getInstance(CryptoOperationsFactory.JCE);
        System.out.println("IdP core object now initialized");        
    }

    public Object processRequest(Object req) throws IOException, ClassNotFoundException {
        String reqString = null;
        Object fjass=null;
        // Should IS always be returned in encrypted form?
        boolean encryptedIS = Config.getProperty("ENCRYPTED_IS", "no").equalsIgnoreCase("yes"); 

        try {
            IdentityStatementIssuer ai = IdentityStatementIssuer.getInstance(myCrOp);
            if (req instanceof String) {
                System.out.println("Request for local identity statement");
                fjass = ai.issueLocalIdentityStatement((String)req);
            } else if (req instanceof IdentityStatement) {
                System.out.println("Request for guest identity statement");
                fjass = ai.issueCrossDomainJavaIdentityStatement((IdentityStatement)req);
            } else if (req instanceof TPMiSRequest) {
                System.out.println("Request for LK certification");
                fjass = ai.issueTPMIdentityStatement((TPMiSRequest)req);
                System.out.println(fjass.toString());
            } else return null;

            // Return response object
            if (fjass instanceof Exception) {
                //Exception e = (Exception)fjass;
                //e.printStackTrace();
            } else if (fjass instanceof IdentityStatement)
                // Check with config info if the IS should be encrypted
                if (encryptedIS) 
                    fjass = new EncryptedIdentityStatement((IdentityStatement)fjass,myCrOp);
            return fjass;
        } catch (Exception e) {
            return new GismoIdmException(e.getMessage());
        }
    }
    
    

}
